<template>
  <view class="partner-publish-page">
    <!-- 自定义头部 -->
    <view class="custom-header">
      <view class="header-left" @click="navigateBack">
        <text class="back-icon">←</text>
        <text class="header-title">找搭子，就来{{globalConfig.name}}</text>
      </view>
      <view class="header-right">
        <text class="iconfont icon-more" @click="openMoreMenu"></text>
        <text class="iconfont icon-scan"></text>
      </view>
    </view>

    <!-- 顶部半透明卡片区 -->
    <view class="top-glass-card glass">
      <input class="title-input" type="text" placeholder="请输入标题，如：三缺一" placeholder-style="color: #bbb"
        v-model="form.title" @input="handleTitleInput" />
      <view class="form-row">
        <view class="form-item" @click="form.startTimeShow = true">
          <text class="item-label">开始时间</text>
          <text class="item-value">{{ form.startTime || '请选择' }}</text>
        </view>
        <view class="form-item" @click="form.endTimeShow = true">
          <text class="item-label">结束时间</text>
          <text class="item-value">{{ form.endTime || '请选择' }}</text>
        </view>
      </view>
      <view class="form-row">
        <view class="form-item" @click="openActivityTypeSelector">
          <text class="item-label">活动类型</text>
          <text class="item-value">{{ form.activityType || '请选择' }}</text>
        </view>
        <view class="form-item" @click="openStoreSelector">
          <text class="item-label">选择门店</text>
          <text class="item-value">{{ form.store || '请选择' }}</text>
        </view>
        <view class="form-item" @click="openPeopleCountSelector">
          <text class="item-label">找搭人数</text>
          <text class="item-value">{{ form.peopleCount || '请选择' }}</text>
        </view>
      </view>
      <view class="gender-row">
        <view class="gender-tag" :class="{ active: form.gender === 'all' }" @click="form.gender = 'all'">
          男女不限
        </view>
        <view class="gender-tag" :class="{ active: form.gender === 'male' }" @click="form.gender = 'male'">
          仅限男生
        </view>
        <view class="gender-tag" :class="{ active: form.gender === 'female' }" @click="form.gender = 'female'">
          仅限女生
        </view>
      </view>
    </view>

    <!-- 信息选择列表区 -->
    <view class="form-list">
      <!-- 活动类型 -->
      <view class="form-item-row" @click="openActivityTypeSelector">
        <text class="item-label">活动类型</text>
        <view class="item-content">
          <text class="content-text">{{ form.activityType || '点击选择' }}</text>
        </view>
      </view>

      <!-- 活动标题 -->
      <view class="form-item-row">
        <text class="item-label">活动标题</text>
        <view class="item-content">
          <input class="title-input-inner" type="text" placeholder="请输入..." placeholder-style="color: #bbb"
            v-model="form.title" />
        </view>
      </view>

      <!-- 选择门店 -->
      <view class="form-item-row" @click="openStoreSelector">
        <text class="item-label">选择门店</text>
        <view class="item-content">
          <text class="content-text">{{ form.store || '请选择' }}</text>
        </view>
      </view>

      <!-- 开始时间 -->
      <view class="form-item-row" @click="form.startTimeShow = true">
        <text class="item-label">开始时间</text>
        <view class="item-content">
          <view class="time-btn time-start">
            <text>{{ form.startTime || '请选择' }} </text>
          </view>
        </view>
      </view>

      <!-- 结束时间 -->
      <view class="form-item-row" @click="form.endTimeShow = true">
        <text class="item-label">结束时间</text>
        <view class="item-content">
          <view class="time-btn time-start">
            <text>{{ form.endTime || '请选择' }} </text>
          </view>
        </view>
      </view>

      <!-- 找搭人数 -->
      <view class="form-item-row" @click="openPeopleCountSelector">
        <text class="item-label">找搭人数</text>
        <view class="item-content">
          <text class="content-text">{{ form.peopleCount || '请选择' }}</text>
        </view>
      </view>

      <!-- 搭子意向选择 -->
      <view class="gender-select-row">
        <text class="item-label">搭子意向</text>
        <view class="gender-btn-group">
          <view class="gender-btn" :class="{ active: form.gender === 'all' }" @click="form.gender = 'all'">
            男女不限
          </view>
          <view class="gender-btn" :class="{ active: form.gender === 'male' }" @click="form.gender = 'male'">
            仅限男生
          </view>
          <view class="gender-btn" :class="{ active: form.gender === 'female' }" @click="form.gender = 'female'">
            仅限女生
          </view>
        </view>
      </view>

      <!-- 发布按钮 -->
      <button class="publish-btn" :loading="loading" @click="handlePublish">
        发布找搭子
      </button>
    </view>

    <!-- 底部弹窗：更多操作 -->
    <u-popup ref="morePopup" mode="bottom" @close="closeMorePopup">
      <view class="more-popup-content">
        <view class="popup-item" @click="handleReport">举报</view>
        <view class="popup-item" @click="handleHelp">帮助</view>
      </view>
    </u-popup>

    <!-- 活动类型选择器 -->
    <u-popup ref="activityPopup" mode="bottom" @close="closeActivityPopup">
      <view class="activity-grid-popup">
        <!-- 弹窗头部 -->
        <view class="activity-popup-header">
          <image src="/static/logo.png" class="popup-logo"></image>
          <text class="popup-slogan">找搭子 来{{globalConfig.name}}</text>
          <text class="popup-close" @click="closeActivityPopup">×</text>
        </view>

        <!-- 活动类型网格 -->
        <view class="activity-grid">
          <view class="activity-grid-item" v-for="(type, index) in activityTypes" :key="type.id"
            @click="handleActivityTypeSelect(type)" v-if="type.id != '-1'">
            <image :src="globalConfig.site_url + type.image" class="activity-icon"></image>
            <text class="activity-name">{{ type.name }}</text>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 人数选择器 -->
    <u-popup ref="peoplePopup" mode="bottom" @close="closePeoplePopup">
      <view class="people-selector-popup">
        <view class="popup-title">选择人数</view>
        <view class="people-grid">
          <view class="people-btn" v-for="num in 8" :key="num" :class="{ selected: form.peopleCount == num }"
            @click="selectPeople(num)">
            {{ num }}人
          </view>
          <view class="people-btn custom-people" @click="openCustomPeopleInput">
            自定义
          </view>
        </view>
      </view>
    </u-popup>


    <u-picker mode="time" v-model="form.startTimeShow" :params="form.params" @confirm="onStartTimeChange"></u-picker>
    <u-picker mode="time" v-model="form.endTimeShow" :params="form.params" @confirm="onEndTimeChange"></u-picker>
  </view>
</template>

<script>
// 引入实际接口（需替换为你的接口文件路径）
import { publishPartner } from '@/api/partner.js'
import { mapGetters, mapActions, mapState } from 'vuex';

export default {
  data() {
    return {
      form: {
        startTimeShow: false,
        endTimeShow: false,
        params: {
          year: true,
          month: true,
          day: true,
          hour: true,
          minute: true,
          second: false
        },
        title: '',          // 活动标题
        gender: 'all',      // 搭子性别意向：all/male/female
        activityType: '',   // 活动类型
        store: '',    // 门店
        startTime: '',      // 开始时间
        endTime: '',        // 结束时间
        peopleCount: '',    // 找搭人数
        longitude: '',      // 经度
        latitude: '',       // 纬度
  shopId: '',         // 店铺ID
  selectedShop: null  // 选中的店铺数据
      },
      loading: false,       // 发布按钮加载状态
    selectedShop: null,    // 选中的店铺数据

    // 底部弹窗
    morePopup: null
    }
  },
  computed: {
    activityTypes() {
      return this.$store.getters.getActivityTypes
    },
    // 使用mapGetters获取全局状态
    ...mapGetters([
      'getGaodeKey',
      'getSiteName'
    ]),

    // 使用mapState直接访问state
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
    })
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack()
    },

    // 输入标题（实时处理）
    handleTitleInput(e) {
      this.form.title = e.detail.value
    },

    // 打开活动类型选择器
    openActivityTypeSelector() {
      this.$refs.activityPopup.open()
    },

    // 关闭活动类型选择器
    closeActivityPopup() {
      // 可扩展逻辑
    },

    // 打开门店选择器
    openStoreSelector() {
      if (!this.form.activityTypeID) {
        uni.showToast({ title: '请先选择活动类型', icon: 'none' });
        return;
      }
      uni.navigateTo({ url: `/pages/shop/shopList?type_id=${this.form.activityTypeID}` });
    },

    // 打开开始时间选择器
    openStartTimePicker() {
      if (this.$refs.startTimePicker) {
        this.$refs.startTimePicker.open()
      } else {
        console.error('startTimePicker ref not found')
      }
    },

    // 打开结束时间选择器
    openEndTimePicker() {
      if (this.$refs.endTimePicker) {
        this.$refs.endTimePicker.open()
      } else {
        console.error('endTimePicker ref not found')
      }
    },

    // 开始时间选择器处理
    onStartTimeChange(e) {
      console.log(e, 'onStartTimeChange');
      const { year, month, day, hour, minute } = e;
      // 格式化时间为 YYYY-MM-DD HH:MM 格式
      this.form.startTime = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
      // 如果结束时间早于开始时间，重置结束时间
      if (this.form.endTime && new Date(this.form.endTime) <= new Date(this.form.startTime)) {
        this.form.endTime = '';
      }
      // 更新顶部区域显示
      this.updateTopSection();
    },

    // 结束时间选择器处理
    onEndTimeChange(e) {
      console.log(e, 'onEndTimeChange');
      const { year, month, day, hour, minute } = e;
      // 格式化时间为 YYYY-MM-DD HH:MM 格式
      this.form.endTime = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
      // 更新顶部区域显示
      this.updateTopSection();
    },

    // 获取地理位置
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.form.longitude = res.longitude.toString();
          this.form.latitude = res.latitude.toString();
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          uni.showToast({
            title: '获取位置失败，请开启定位权限',
            icon: 'none'
          });
        }
      });
    },

    // 获取结束时间的最小值（不能早于开始时间）
    getEndTimeStart() {
      return this.form.startTime || '2020-01-01 00:00'
    },

    // 打开人数选择器
    openPeopleCountSelector() {
      this.$refs.peoplePopup.open()
    },

    // 关闭人数选择器
    closePeoplePopup() {
      // 可扩展逻辑
    },

    // 人数选择处理
    selectPeople(num) {
      this.form.peopleCount = num
      this.$refs.peoplePopup.close()
      // 更新顶部区域显示
      this.updateTopSection()
    },

    // 自定义人数输入
    openCustomPeopleInput() {
      uni.showModal({
        title: '自定义人数',
        content: '',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            const input = parseInt(res.content)
            if (!isNaN(input) && input > 0 && input <= 20) {
              this.form.peopleCount = input
              // 更新顶部区域显示
              this.updateTopSection()
            } else {
              uni.showToast({
                title: '请输入1-20之间的有效数字',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    // 门店选择处理
      handleStoreSelect(store) {
        this.form.store = store.name;
        this.updateTopSection();
      },

      // 活动类型选择处理
      handleActivityTypeSelect(type) {
      this.form.activityType = type.name
      this.form.activityTypeID = type.id
      this.$refs.activityPopup.close()
      // 更新顶部区域显示
      this.updateTopSection()
    },

    // 自定义活动类型
    handleCustomActivity() {
      uni.showModal({
        title: '自定义活动类型',
        content: '',
        editable: true,
        success: (res) => {
          if (res.confirm && res.content.trim()) {
            this.form.activityType = res.content.trim()
            // 更新顶部区域显示
            this.updateTopSection()
          }
        }
      })
    },

    // 打开更多操作弹窗
    openMoreMenu() {
      this.$refs.morePopup.open()
    },

    // 关闭更多操作弹窗
    closeMorePopup() {
      // 可扩展逻辑（如埋点）
    },
    // 表单校验
    validateForm() {
      if (!this.form.title.trim()) {
        uni.showToast({ title: '请输入活动标题', icon: 'none' })
        return false
      }
      if (!this.form.activityType) {
        uni.showToast({ title: '请选择活动类型', icon: 'none' })
        return false
      }
      if (!this.form.store) {
        uni.showToast({ title: '请选择门店', icon: 'none' })
        return false
      }
      if (!this.form.startTime) {
        uni.showToast({ title: '请选择开始时间', icon: 'none' })
        return false
      }
      if (!this.form.endTime) {
        uni.showToast({ title: '请选择结束时间', icon: 'none' })
        return false
      }
      if (new Date(this.form.endTime) <= new Date(this.form.startTime)) {
        uni.showToast({ title: '结束时间必须晚于开始时间', icon: 'none' })
        return false
      }
      if (!this.form.peopleCount) {
        uni.showToast({ title: '请选择找搭人数', icon: 'none' })
        return false
      }
      if (!this.form.longitude || !this.form.latitude) {
        uni.showToast({ title: '无法获取位置信息，请重试', icon: 'none' });
        return false;
      }
      return true
    },

    // 发布找搭子（核心逻辑）
    async handlePublish() {
      if (!this.validateForm()) return // 校验不通过则返回

      this.loading = true
      try {
        // 调用发布接口（替换为你的实际接口逻辑）
        const res = await publishPartner({
          type_id: this.form.activityTypeID,
          title: this.form.title,
          shop_title: this.form.store,
          start_time: this.form.startTime ? new Date(this.form.startTime).getTime() : 0,
          end_time: this.form.endTime ? new Date(this.form.endTime).getTime() : 0,
          max_members: this.form.peopleCount,
          sex: this.form.gender === 'all' ? 1 : this.form.gender === 'male' ? 2 : 3,
          long: this.form.longitude,
          lat: this.form.latitude
        })

        if (res.data.code == 1) {
          uni.showToast({ title: res.msg || '发布成功', icon: 'success' })
          // 发布成功后返回上一页并刷新
          setTimeout(() => {
            uni.navigateBack()
          }, 500);
        } else {
          uni.showToast({ title: res.msg || '发布失败，请重试', icon: 'none' })
        }
      } catch (error) {
        console.error('发布失败：', error)
        uni.showToast({ title: '发布失败，请重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 格式化日期时间显示
    formatDateTime(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    // 更新顶部区域显示
    updateTopSection() {
      // 由于是数据绑定，Vue会自动更新视图
      // 这里可以添加其他自定义逻辑
      this.topSection = {
        title: this.form.title,
        activityType: this.form.activityType,
        store: this.form.store,
        time: `${this.form.startTime} - ${this.form.endTime}`,
        peopleCount: this.form.peopleCount
      }
    }
  },
  onShow() {
    console.log(this.$store.state.selectedShop, 'selectedShop');
     this.form.store = this.$store.state.selectedShop.name || ''
     this.form.storeId = this.$store.state.selectedShop.id || ''
    },

    beforeDestroy() {
      // 移除事件监听
      uni.$off('shopSelected', this.shopSelectedHandler);
    },

    mounted() {
    // 初始化顶部区域显示
    this.updateTopSection();
    // 获取地理位置
    this.getLocation();
  },
}
</script>

<style scoped>
/* 页面整体样式 */
.partner-publish-page {
  min-height: 100vh;
  background-color: #1a191e;
  padding-top: 20rpx;
  color: #fff;
}

/* 自定义头部 */
.custom-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #1a191e;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 36rpx;
  color: #fff;
  margin-right: 10rpx;
}

.header-title {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

/* 顶部半透明卡片 */
.top-glass-card {
  margin: 0 30rpx 30rpx;
  padding: 20rpx;
  border-radius: 20rpx;
}

.glass {
  backdrop-filter: blur(10rpx);
  background-color: rgba(255, 255, 255, 0.1);
}

.title-input {
  width: 100%;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 28rpx;
  color: #fff;
  background-color: transparent;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 20rpx;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.form-item {
  width: calc(50% - 10rpx);
  height: 50rpx;
  line-height: 50rpx;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 10rpx;
  text-align: center;
  font-size: 24rpx;
  color: #bbb;
  position: relative;
}

.form-item picker {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  /* opacity: 0;// */
}

.gender-row {
  display: flex;
  justify-content: space-between;
  gap: 15rpx;
}

.gender-tag {
  flex: 1;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  border-radius: 10rpx;
  font-size: 24rpx;
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.gender-tag.active {
  background: linear-gradient(90deg, #9c6cfe, #ff8dd3);
  border: none;
}

/* 表单列表区 */
.form-list {
  margin: 0 30rpx;
}

.form-item-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  cursor: pointer;
}

.item-label {
  font-size: 28rpx;
  color: #fff;
}

.item-content {
  display: flex;
  align-items: center;
  color: #bbb;
  font-size: 26rpx;
  text-align: right;
}

.icon-right {
  font-size: 32rpx;
  margin-left: 10rpx;
}

.picker {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 搭子意向选择 */
.gender-select-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.gender-btn-group {
  display: flex;
  gap: 20rpx;
}

.gender-btn {
  padding: 8rpx 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
}

.gender-btn.active {
  background: linear-gradient(90deg, #9c6cfe, #ff8dd3);
  border: none;
}

/* 发布按钮 */
.publish-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(90deg, #734eff, #ff7dc2);
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  margin-top: 40rpx;
}

/* 图标字体（需确保已引入 iconfont 或替换为 uni-icons） */
.iconfont {
  font-family: "iconfont" !important;
  font-size: inherit;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-more::before {
  content: "\e602";
  /* 替换为实际 iconfont 代码 */
}

.icon-scan::before {
  content: "\e603";
  /* 替换为实际 iconfont 代码 */
}

.icon-right::before {
  content: "\e604";
  /* 替换为实际 iconfont 代码 */
}

/* 活动类型弹窗样式 */
.activity-grid-popup {
  padding: 30rpx;
}

.activity-popup-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  position: relative;
}

.popup-logo {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
}

.popup-slogan {
  margin-left: 20rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  position: absolute;
  right: 0;
  font-size: 40rpx;
  color: #999;
}

.activity-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}

.activity-grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 15rpx;
}

.activity-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 15rpx;
}

.activity-name {
  font-size: 28rpx;
  color: #333;
}

.custom-activity {
  border: 2rpx dashed #ccc;
}

.custom-icon {
  font-size: 60rpx;
  color: #999;
}

/* 人数选择器样式 */
.people-selector-popup {
  padding: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx 0;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.people-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20rpx;
  padding: 20rpx 0;
}

.people-btn {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.people-btn.selected {
  background: linear-gradient(90deg, #9c6cfe, #ff8dd3);
  color: white;
}

.custom-people {
  background-color: #e8f0fe;
  color: #409eff;
}
</style>
